﻿#include <QEventLoop>
#include "MainWindow.h"
#include "qtimer.h"
#include "qpushbutton.h"
#include "./ui_MainWindow.h"
#include "once_trigger/utils/utils.h"
#include "libdaq/device/base_device.h"
#include "once_trigger/connect_page/connect_page.h"

using namespace libdaq::device;

MainWindow::MainWindow(QWidget *parent)
  : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  qRegisterMetaType<std::vector<std::vector<float> > >("std::vector<std::vector<float>>");
  // 创建设备
  base_device_ = NewDevice();
  connect(ui->Connnectbutton, &QPushButton::clicked, this, &MainWindow::ClickConnectAction);
  connect(ui->StartADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStartADCCollectionAction);
  connect(ui->UpdateConfig, &QPushButton::clicked, this, &MainWindow::ClickUpdateConfig);
  connect(ui->OnceCollection, &QPushButton::clicked, this, &MainWindow::ClickSoftwareTrigger);
  connect(ui->StopADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStopADCCollection);

  // 初始化通道数据存储和状态
  channel_data_.resize(8);
  channel_complete_.resize(8);

  InitWaveWidget();
}

MainWindow::~MainWindow() {
  delete ui;
}

void MainWindow::ConnectStatusSlot(bool status, ConnectPage::ConnectType type) {
  if (status) {
    connected_count++;
    if (!base_device_->InitializeDevice()) {
      qWarning(u8"初始化设备失败，请检查配置参数是否存在错误");
      return;
    }
    if (!base_device_->ConnectedDevice()) {
      qWarning(u8"发送连接设备命令失败");
      return;
    }
    // TODO:延时确保配置正常下发
    QEventLoop loop;
    QTimer::singleShot(100, &loop, SLOT(quit()));
    loop.exec();


  } else{
    base_device_->DisconnectedDevice();
  }
}

void MainWindow::ClickConnectAction() {
  ConnectPage connect_page(base_device_, nullptr);
  // 初始化连接界面
  if (connect_page_.isNull()) {
    connect_page_.reset(new ConnectPage(base_device_));
    connect_page_->setModal(false);
    connect(connect_page_.get(), &ConnectPage::ConnectStatus, this, &MainWindow::ConnectStatusSlot);
  }
  connect_page_->InitParams(base_device_);
  connect_page_->show();
}

void MainWindow::ClickStartADCCollectionAction() {
  if(!base_device_->StartADCCollection()){
    qWarning(u8"启动ADC采集失败");
    return;
  }
  qInfo(u8"启动ADC采集成功");
}

void MainWindow::ClickUpdateConfig() {
  // 采样率 800K
    auto legal_sample_rate = base_device_->GetADCLegalSampleRate();
  if (!base_device_->ConfigADCSampleRate(libdaq::device::LockzhinerADCSampleRate::ADCSampleRate_800_K)) {
        qWarning(u8"采样率配置失败");
    }
  // 电压量程 10V
    if (!base_device_->ConfigADCVoltage(libdaq::device::LockzhinerADCVoltage::ADCVoltage_10_V)) {
        qWarning(u8"电压量程配置失败");
    }
  // 8通道使能
    if (!base_device_->ConfigADCChannel(0xFF)) {
        qWarning(u8"ADC4通道配置失败");
    }
  // 触发电平 0mv
    uint32_t level=0;
  // 双边缘触发 单次采集 软件触发
    auto type = static_cast<libdaq::device::LockzhinerADCTriggerType>(libdaq::device::LockzhinerADCTriggerType::DoubleEdge);
    auto mode = static_cast<libdaq::device::LockzhinerADCTriggerMode>(libdaq::device::LockzhinerADCTriggerMode::Single);
    auto channel = static_cast<libdaq::device::LockzhinerADCChannel>(libdaq::device::LockzhinerADCChannel::ADCChannelAINNone);
    if (!base_device_->ConfigADCTrigger(type, mode, channel, level)) {
        qWarning(u8"DAQ控制器配置ADC触发失败");
    }

  // 长度 4920个点
    if (!base_device_->ConfigADCTriggerLength(4920)) {
        qWarning(u8"触发长度配置失败");
    }
  // 超时 100ms
    if (!base_device_->ConfigTriggerTimeout(100)) {
        qWarning(u8"超时时间配置失败");
    }
    qInfo(u8"下发配置成功");
}

void MainWindow::ClickSoftwareTrigger()
{
  if(!base_device_->ConfigADCTriggerSource
  (static_cast<uint8_t>(libdaq::device::DAQADCTriggerSource::TriggerSourceSoftware))){
    qWarning(u8"软件触发失败");
    return;
  }
  
  // 停止并清理之前的线程
  for (auto& thread : once_trigger_adc_thread_list_) {
    if (thread != nullptr) {
      thread->quit();
      thread->deleteLater();
    }
  }
  once_trigger_adc_thread_list_.clear();
  
  // 重置通道数据和状态
  for (int i = 0; i < 8; ++i) {
    channel_data_[i].clear();
    channel_complete_[i] = false;
  }


  // 为每个启用的通道创建一个线程
  for (int channel = 0; channel < 8; ++channel) {
    auto thread = QSharedPointer<OnceTriggerADCThread>::create(base_device_, channel, channel_data_[channel]);
    connect(thread.get(), &OnceTriggerADCThread::complete, this, &MainWindow::OnChannelDataComplete);
    once_trigger_adc_thread_list_.append(thread);
    thread->start();
  }

  qInfo(u8"软件触发成功");
}

void MainWindow::OnChannelDataComplete(int channel) {
  qInfo(u8"通道 %d 数据采集完成", channel);
  
  // 标记该通道已完成
  channel_complete_[channel] = true;
  
  // 检查所有通道是否都完成了
  bool all_complete = true;
  for (int i = 0; i < channel_complete_.size(); ++i) {
    if (!channel_complete_[i]) {
      all_complete = false;
      break;
    }
  }
  
  // 如果所有通道都完成了，更新图表
  if (all_complete) {
    UpdatePlotData();
  }
}

void MainWindow::ClickStopADCCollection()
{
  if(!base_device_->StopADCCollection()){
    qWarning(u8"停止ADC采集失败");
    return;
  }
  
  // 停止并清理所有线程
  for (auto& thread : once_trigger_adc_thread_list_) {
    if (thread != nullptr) {
      thread->quit();
      thread->deleteLater();
    }
  }
  once_trigger_adc_thread_list_.clear();
  
  qInfo(u8"停止ADC采集成功");
}

void MainWindow::InitWaveWidget() {
  QVector<QColor> channel_color_ = {
    // 通道颜色
    QColor(0x00, 0x80, 0x00), // 深绿色
    QColor(0xdc, 0x14, 0x3c), // 深红色
    QColor(0x00, 0x8b, 0x8b), // 深青色
    QColor(0xda, 0xa5, 0x20), // 金色
    QColor(0x80, 0x00, 0x80), // 深紫色
    QColor(0x00, 0x00, 0x8b), // 深蓝色
    QColor(0xd2, 0x69, 0x1e), // 深橙色
    QColor(0x48, 0x3d, 0x8b) // 深紫蓝色
  };

  base_wave_widget_ = QSharedPointer<BaseWaveWidget>::create();
  base_wave_widget_->InitChannel(8, channel_color_);
  ui->stackedWidget->addWidget(base_wave_widget_.get());
  ui->stackedWidget->setCurrentWidget(base_wave_widget_.get());
}

void MainWindow::UpdatePlotData() {
    // 检查数据是否为空
    bool is_empty = true;
    for (const auto &i: channel_data_) {
        if (!i.empty()) {
            is_empty = false;
            break;
        }
    }
    if (is_empty) {
        return;
    }

    auto trigger_type = base_device_->GetCurrentTriggerType();
    if (trigger_type != LockzhinerADCTriggerType::Normal) {
        // 触发类型不为滚动模式 清空之前的数据
        base_wave_widget_->Clear();
    }
    
    // 添加数据到图表
    for (int i = 0; i < channel_data_.size(); ++i) {
        for (int j = 0; j < channel_data_[i].size(); ++j) {
            base_wave_widget_->AddData(i, channel_data_[i][j]);
        }
    }

    // 更新图表
    UpdateAutoScale();
    base_wave_widget_->replot(QCustomPlot::rpQueuedReplot);
    
    // 数据显示完成后停止并清理所有线程
    for (auto& thread : once_trigger_adc_thread_list_) {
        if (thread != nullptr) {
            thread->quit();
            thread->deleteLater();
        }
    }
    once_trigger_adc_thread_list_.clear();
}

void MainWindow::UpdateAutoScale() {
    uint32_t a=4920;
    base_wave_widget_->xAxis->setRange(0, a);
}
